<?php

namespace App\Models;

use App\Models\Traits\HasSlug;
use App\Models\Traits\ListAble;
use App\Models\Traits\SortAble;
use App\Scopes\DraftScope;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Article extends Model
{
    use SoftDeletes, HasSlug;
    use ListAble;
    use SortAble;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['published_at', 'created_at', 'deleted_at'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'last_user_id',
        'category_id',
        'title',
        'subtitle',
        'slug',
        'cover',
//        'content',
        'meta_description',
        'is_draft',
        'is_original',
        'published_at',
    ];

    protected $casts = [
        'content' => 'array',
    ];

    /**
     * The "booting" method of the model.
     */
    public static function boot()
    {
        parent::boot();

        static::addGlobalScope(new DraftScope());
    }

    protected static $allowSearchFields = ['title', 'excerpt'];
    protected static $allowSortFields = ['title', 'status', 'views_count', 'top', 'order', 'published_at', 'category_id'];
    protected static $directory = 'articles';



    public function scopeRecent($query)
    {
        return $query->orderBy('published_at', 'desc')->orderBy('created_at', 'desc');
    }
    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id');
    }

    public function scopeApplyFilter($query, $data)
    {
        $data = $data->only('only_trashed', 'category_id');

        $query->byCategory(isset($data['category_id']) ? $data['category_id'] : null);
        if (isset($data['only_trashed']) && $data['only_trashed']) {
            $query->onlyTrashed();
        }
        return $query->recent();
    }

    public function scopeByCategory($query, $category)
    {
        if ($category instanceof Category) {
            $category = $category->id;
        } else {
            $category = intval($category);
        }
        if ($category){
            $query->where('category_id', $category);
        }
    }


    public function addViewCount()
    {
        return $this->increment('view_count');
    }





    /**
     * Get the user for the blog article.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the tags for the blog article.
     *
     * @return \Illuminate\Database\Eloquent\Relations\morphToMany
     */
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }

    /**
     * Get the comments for the discussion.
     *
     * @return \Illuminate\Database\Eloquent\Relations\morphMany
     */
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }

    /**
     * 一对一关联 articleContent 表
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function articleContent()
    {
        return $this->hasOne(ArticleContent::class);
    }

    /**
     * Get the created at attribute.
     *
     * @param $value
     *
     * @return string
     */
    public function getCreatedAtAttribute($value)
    {
        return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $value)->diffForHumans();
    }

    /**
     * Set the title and the readable slug.
     *
     * @param string $value
     */
//    public function setTitleAttribute($value)
//    {
//        $this->attributes['title'] = $value;
//
//        if (!config('services.youdao.appKey') || !config('services.youdao.appSecret')) {
//            $this->setUniqueSlug($value, str_random(5));
//        } else {
//            $this->setUniqueSlug(translug($value), '');
//        }
//    }



//    /**
//     * Set the content attribute.
//     *
//     * @param $value
//     */
//    public function setContentAttribute($value)
//    {
//        $data = [
//            'raw' => $value,
//            'html' => (new Markdowner())->convertMarkdownToHtml($value),
//        ];
//
//        $this->attributes['content'] = json_encode($data);
//    }


    public function scopeCheckAuth($query)
    {
        if (auth()->check() && auth()->user()->is_admin) {
            $query->withoutGlobalScope(DraftScope::class);
        }
        return $query;
    }
}
